import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse, AxiosError,InternalAxiosRequestConfig } from 'axios';

// Create Axios instance with global configuration
const api: AxiosInstance = axios.create({
    baseURL: 'https://127.0.0.1:8080', // Replace with your API base URL
    timeout: 10000, // Request timeout in milliseconds
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
    },
});

// Request Interceptor
api.interceptors.request.use(
    (config: InternalAxiosRequestConfig) => {
        // Add authentication token to headers if available
        const token = localStorage.getItem('authToken'); // Example: Retrieve token from localStorage
        if (token && config.headers) {
            config.headers.Authorization = `Bearer ${token}`;
        }

        // Log request for debugging (optional)
        console.log('Request:', config.method?.toUpperCase(), config.url);

        return config;
    },
    (error: AxiosError) => {
        // Handle request errors
        console.error('Request Error:', error.message);
        return Promise.reject(error);
    }
);

// Response Interceptor
api.interceptors.response.use(
    (response: AxiosResponse) => {
        // Handle successful responses
        console.log('Response:', response.status, response.data);
        return response;
    },
    (error: AxiosError) => {
        // Handle response errors
        if (error.response) {
            // Server responded with a status code outside 2xx
            switch (error.response.status) {
                case 401:
                    // Handle unauthorized access (e.g., redirect to login)
                    console.error('Unauthorized: Redirecting to login...');
                    // Example: window.location.href = '/login';
                    break;
                case 403:
                    console.error('Forbidden: Access denied');
                    break;
                case 500:
                    console.error('Server Error: Please try again later');
                    break;
                default:
                    console.error(`Error ${error.response.status}: ${error.response.data}`);
            }
        } else if (error.request) {
            // No response received
            console.error('No Response:', error.message);
        } else {
            // Error setting up the request
            console.error('Request Setup Error:', error.message);
        }

        return Promise.reject(error);
    }
);

export default api;